#include <qyam3dview.h>
#include <graphics/utils.h>
#include <assert.h>
#include <render/glextensions.h>

QYam3DView::QYam3DView(QWidget *parent) :
    QGLWidget(parent)
    , m_pfCreateScene(0)
    , m_scene(0)
    , m_initRequested(false)
{
}

QYam3DView::~QYam3DView()
{
    if( m_scene != 0 )
    {
        delete m_scene;
        m_scene = 0;
    }
}

void QYam3DView::setSceneCreateFunc(SceneCreateFuncType pfCreateScene)
{
    m_pfCreateScene = pfCreateScene;

    if( m_initRequested )
    {
        init();
    }
}

QSize QYam3DView::minimumSizeHint() const
{
    return QSize(50, 50);
}

QSize QYam3DView::sizeHint() const
{
    return QSize(400, 400);
}


void QYam3DView::resizeGL(int width, int height)
{
    if( m_scene != 0 )
    {
        m_scene->resize(width,height);
    }
}

void QYam3DView::initializeGL()
{
    m_initRequested = true;
    if( m_pfCreateScene != 0 )
    {
        init();
    }
}

void QYam3DView::update()
{
    float deltaTime=0.02f;

    if( m_scene != 0 )
    {
        m_scene->update(deltaTime);
    }

    updateGL(); // Update base class (this calls paintGL())
}

void QYam3DView::paintGL()
{
    // Clear background with blue. Clear Z-buffer.
    qglClearColor(Qt::blue);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if( m_scene != 0 )
    {
        m_scene->render();
    }
}

void QYam3DView::init()
{
    assert( m_pfCreateScene != 0 );
    assert( m_scene == 0 );
    assert( m_initRequested == true );

    if (!getGLExtensionFunctions().resolve(context()))
    {
        QMessageBox::critical(0, "OpenGL features missing",
            "Failed to resolve OpenGL functions required to run this demo.\n" );
        return;
    }

    m_scene = m_pfCreateScene();
    m_scene->resize(width(),height());
    assert( m_scene != 0 );
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(update()));
    m_timer.start( 20 );
}


